const wm = require('webpack-merge'),
      w  = require('webpack'),
      hp = require('html-webpack-plugin'),
      cp = require('clean-webpack-plugin'),
      ex = require('extract-text-webpack-plugin'),
      path = require('path');

const baseConfig = {
    entry: {
       react: 'react',
    },
    output: {
        path: path.resolve(__dirname, 'dist/'),
        filename: 'js/[name].[chunkHash].js'
    },
    resolve: {
        extensions: ['.js', '.json', '.vue', '.scss', '.css']
    },
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ex.extract({
                    fallback: 'style-loader',
                    use: [{
                        loader: 'css-loader'
                    }]
                })
            }
        ]
    }
    ,
    plugins: [
        new cp(path.resolve(__dirname, 'dist')),
        new w.optimize.CommonsChunkPlugin({
            name: 'react',
            minChunks: Infinity // 希望打包出来的只要它自己没有别的
        }),
        new ex({ // 配合html-webpack-plugin 直接插入到页面中。
            filename: 'css/[name].[hash].css'
        })
    ]
};
/**
 * 生成配置页面
 */
const generatorPage = function({
    title = '',
    entry = '',
    template = './index.html',
    name = '',
    chunks = []
} = {}){
    return {
        entry,
        plugins: [
            new hp({
                title,
                chunks,
                template,
                filename: name + '.html'
            })
        ]
    }
}

const pages = [
    generatorPage({
        title: 'pageA',
        entry: {
            pageA: path.resolve(__dirname, 'src/pages/a.js')
        },
        name: 'pageA',
        chunks: ['react', 'pageA']
    }),
    generatorPage({
        title: 'pageB',
        entry: {
            pageB: path.resolve(__dirname, 'src/pages/b.js')
        },
        name: 'pageB',
        chunks: ['react', 'pageB']
    }),
    generatorPage({
        title: 'pageC',
        entry: {
            pageC: path.resolve(__dirname, 'src/pages/c.js')
        },
        name: 'pageC',
        chunks: ['react', 'pageC']
    }),
];

// 经过分析发现webpack@3.12.0通过多配置的情况也可以抽离react仅仅创建了一个。
// 和多配置不同是这里把所有配置合成一个而不是多个。
// module.exports 可以返回数组并且执行每一个元素
/*module.exports = pages.map(page => {
    return wm(baseConfig, page);
})*/
//merge 可以是数组合并多个
module.exports = wm([baseConfig].concat(pages));